package com.hk.modules.circuit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hk.common.excel.ExcelReader;
import com.hk.common.utils.StringUtils;
import com.hk.modules.circuit.pojo.CircuitPojo;
import com.hk.modules.circuit.mapper.CircuitMapper;
import com.hk.modules.circuit.pojo.EquipVo;
import com.hk.modules.circuit.pojo.ScreenVo;
import com.hk.modules.circuit.service.CircuitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hk.modules.node.pojo.NodePojo;
import com.hk.modules.node.service.NodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zy
 * @since 2024-04-17
 */
@Service
public class CircuitServiceImpl extends ServiceImpl<CircuitMapper, CircuitPojo> implements CircuitService {

    @Autowired
    private NodeService nodeService;

    @Override
    public List<CircuitPojo> listTree(NodePojo p) {
        return baseMapper.listTree(p);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCircuit(CircuitPojo p) {

        NodePojo queryNode = new NodePojo().setCircuitId(p.getId());
        nodeService.remove(new QueryWrapper<>(queryNode));
        updateById(p);
        if(p.getChildren()!=null&&p.getChildren().size()>0){
            p.getChildren().forEach(item->{
                item.setCircuitId(p.getId());
                item.setCreateTime(new Date()).setUpdateTime(new Date());
            });
            nodeService.saveBatch(p.getChildren());
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCircuit(String id) {
        NodePojo queryNode = new NodePojo().setCircuitId(id);
        nodeService.remove(new QueryWrapper<>(queryNode));
        removeById(id);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCircuit(CircuitPojo p) {

        saveOrUpdate(p);
        if(p.getChildren()!=null&&p.getChildren().size()>0){
            p.getChildren().forEach(item->{
                item.setCircuitId(p.getId());
                item.setCreateTime(new Date()).setUpdateTime(new Date());
            });
            nodeService.saveBatch(p.getChildren());
        }
        return true;
    }

    @Override
    public CircuitPojo getInfo(String id) {
        CircuitPojo tmpObj = getById(id);
        QueryWrapper<NodePojo> queryWrap = new QueryWrapper<>(new NodePojo().setCircuitId(id));
        queryWrap.orderByAsc("order_num");
        List<NodePojo> childNode = nodeService.list(queryWrap);
        tmpObj.setChildren(childNode);
        //
        String empStr = "";
        tmpObj.setScreenList(new ArrayList<>());
        ScreenVo screenVo = new ScreenVo().setEquipList(new ArrayList<>());
        EquipVo equipVo = new EquipVo().setNodeList(new ArrayList<>());
        ScreenVo screenVoPre = null;
        EquipVo equipVoPre = null;
        // 增加前量变量 处理
        for (int i = 0; i < childNode.size(); i++) {
            NodePojo node = childNode.get(i);
            String screenKey = node.getScreenName();
            if(StringUtils.isEmpty(screenKey)) {
                screenKey = empStr;
            }
            String equipKey = node.getEquipName();
            if(StringUtils.isEmpty(equipKey)) {
                equipKey = empStr;
            }
            if(i==0){
                equipVo.setName(equipKey).getNodeList().add(node);
                screenVo.setName(screenKey).getEquipList().add(equipVo);
            }else {
                if(!screenKey.equals(screenVoPre.getName())){
                    tmpObj.getScreenList().add(screenVo);
                    screenVo = new ScreenVo().setEquipList(new ArrayList<>());
                    screenVo.setName(screenKey);
                }

                if(!equipKey.equals(equipVoPre.getName())||!screenKey.equals(screenVoPre.getName())){
                    equipVo = new EquipVo().setNodeList(new ArrayList<>());
                    equipVo.setName(equipKey).getNodeList().add(node);
                    screenVo.getEquipList().add(equipVo);
                }else{
                    equipVo.setName(equipKey).getNodeList().add(node);
                }
            }

            if(i==childNode.size()-1){
                if (!tmpObj.getScreenList().contains(screenVo)){
                    tmpObj.getScreenList().add(screenVo);
                }
            }

            screenVoPre = screenVo;
            equipVoPre = equipVo;
        }

        return tmpObj;
    }

    @Override
    public void uploadFile(MultipartFile file) throws Exception {
        final String PATH_PREFIX="tmp/";

        if(file==null||file.isEmpty()){
            throw new RuntimeException("未选择文件");
        }

        String userDirPath = System.getProperty("user.dir");
        File userDirDir = new File(userDirPath + File.separator + PATH_PREFIX);
        if(!userDirDir.exists()&&!userDirDir.mkdirs()){
            //生成文件夹
            log.error("无法创建文件夹:"+userDirDir.getAbsolutePath());
        }
        // 拿到文件名
        String filename = file.getOriginalFilename();
        // 构建真实的文件路径
        filename =  userDirDir.getAbsolutePath() + File.separator + filename;
        File uploadFile = new File(filename);
        //文件写到服务器，
        file.transferTo(uploadFile);

        List<NodePojo> nodeList = ExcelReader.readExcel(filename);
        if(nodeList!=null){
            Set<String> circuitNameSet = nodeList.stream()
                    .map(NodePojo::getCircuitName)
                    .collect(Collectors.toSet());
            Set<CircuitPojo> circuitSet = new HashSet<>();
            for (String cname: circuitNameSet) {
                circuitSet.add(mergeByName(cname));
            }
            Map<String, CircuitPojo> circuitMap = circuitSet.stream().collect(Collectors
                    .toMap(CircuitPojo::getName, circuitPojo -> circuitPojo));
            for (NodePojo node: nodeList) {
                node.setCircuitId(circuitMap.get(node.getCircuitName()).getId());
            }
            nodeService.saveBatch(nodeList);
        }
    }

    /**
     * 如果有则返回 没有则新增进去
     * @param cname
     * @return
     */
    private CircuitPojo mergeByName(String cname){
        CircuitPojo c = new CircuitPojo().setName(cname);
        QueryWrapper<CircuitPojo> queryWrapper = new QueryWrapper<>(c);
        List<CircuitPojo> list = list(queryWrapper);
        if(list.size()>0){
            return list.get(0);
        }else{
            save(c);
            return c;
        }
    }
}
